import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:renqing/pages/edit.dart';
import 'package:renqing/global.dart';
import 'package:renqing/manager/main_manager.dart';
import 'package:provider/provider.dart';
import 'package:renqing/pages/list_item.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int active = 0;
  double spendingTotal = 0;
  double deSpendingTotal = 0;
  List<Widget> tabs() {
    List<Widget> list = [];
    List<Map> items = [
      {'title': '全部'},
      {'title': '收入'},
      {'title': '支出'},
    ];

    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      list.add(Expanded(
        child: InkWell(
          onTap: () {
            setState(() {
              active = i;
            });
          },
          child: Container(
            padding: EdgeInsets.all(7),
            margin: EdgeInsets.all(2),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: active == i
                      ? Global.mainColor
                      : Global.fontSecondColor.withOpacity(0.5),
                  width: 2,
                  style: BorderStyle.solid,
                ),
              ),
            ),
            child: Center(
              child: Text(
                item['title'],
                style: TextStyle(
                  color: active == i
                      ? Global.mainColor
                      : Global.fontSecondColor.withOpacity(0.5),
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ),
      ));
    }
    return list;
  }

  double getDiff(allLocalCache) {
    setState(() {
      spendingTotal = 0;
      deSpendingTotal = 0;
    });

    allLocalCache.forEach((item) {
      setState(() {
        if (json.decode(item['data'])['spending']) {
          spendingTotal =
              spendingTotal + double.parse(json.decode(item['data'])['co']);
        } else {
          deSpendingTotal =
              deSpendingTotal + double.parse(json.decode(item['data'])['co']);
        }
      });
    });
    return spendingTotal - deSpendingTotal;
  }

  List<Widget> getList(allLocalCache) {
    List<Widget> list = [];
    for (var i = 0; i < allLocalCache.length; i++) {
      var item = json.decode(allLocalCache[i]['data']);
      switch (active) {
        case 0:
          list.add(ListItem(data: item, id: allLocalCache[i]['id']));
          break;
        case 1:
          if (!item['spending'])
            list.add(ListItem(data: item, id: allLocalCache[i]['id']));
          break;
        case 2:
          if (item['spending'])
            list.add(ListItem(data: item, id: allLocalCache[i]['id']));
          break;
        default:
      }
    }
    if (list.length == 0) {
      list = [
        SizedBox(height: 40),
        Center(
          child: Text(
            "暂时没有该类记录，快去记一笔吧！",
            style: TextStyle(
              color: Global.fontSecondColor,
            ),
          ),
        ),
        InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => EditPage(id: '000', data: {
                  "spending": false,
                  "date": DateTime.now().toString().substring(0, 10),
                  "name": "",
                  "relation": "其他",
                  "why": "其他",
                  "co": "",
                  "remark": ""
                }),
              ),
            );
          },
          child: Container(
            width: 120,
            padding: EdgeInsets.all(7),
            margin: EdgeInsets.all(18),
            decoration: BoxDecoration(
              color: Global.mainColor,
              border: Border.all(color: Global.mainColor, width: 1),
              borderRadius: BorderRadius.circular(40),
            ),
            child: Center(
              child: Text(
                '添加新记录',
                style: TextStyle(
                  color: Global.backgroundColor,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ),
      ];
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Global.backgroundColor),
        toolbarHeight: 50,
        elevation: 0,
        title: Text(
          "人情账本",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: Global.backgroundColor,
            fontSize: 15,
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add_circle),
            tooltip: '添加',
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => EditPage(id: '000', data: {
                    "spending": false,
                    "date": DateTime.now().toString().substring(0, 10),
                    "name": "",
                    "relation": "其他",
                    "why": "其他",
                    "co": "",
                    "remark": ""
                  }),
                ),
              );
            },
          )
        ],
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(color: Global.cardBackgroundColor),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              height: 110,
              margin: EdgeInsets.all(10),
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomCenter,
                  colors: [
                    Global.mainColor,
                    Global.mainColor.withOpacity(0.7),
                  ],
                ),
              ),
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        "￥",
                        style: TextStyle(
                          color: Global.backgroundColor,
                          fontSize: 17,
                          fontWeight: FontWeight.w500,
                          height: 2,
                        ),
                      ),
                      Text(
                        getDiff(_mainManager.allLocalCache)
                            .abs()
                            .toStringAsFixed(2),
                        style: TextStyle(
                          color: getDiff(_mainManager.allLocalCache) > 0
                              ? Color(0xFFe84a5f)
                              : Color(0xFF14b1ab),
                          fontSize: 30,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Text(
                        " 收支差（元）",
                        style: TextStyle(
                          color: Global.backgroundColor,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          height: 2.5,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 20),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          " 收礼 ￥${deSpendingTotal.toStringAsFixed(2)}",
                          style: TextStyle(
                            color: Global.backgroundColor,
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      Expanded(
                        child: Text(
                          " 送礼 ￥${spendingTotal.toStringAsFixed(2)}",
                          style: TextStyle(
                            color: Global.backgroundColor,
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.all(8),
              child: Row(children: tabs()),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: getList(_mainManager.allLocalCache),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
